package com.lee.pullrefresh.http;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;

public class HttpTaskExecutor{
	
	private static HttpTaskExecutor mInstance;
	private ExecutorService mExecThreadTool;
	
	public static int FIX_THREAD_POOL_COUNT = 3;
	
	synchronized public static HttpTaskExecutor getInstance() {
		if (mInstance == null) 
			mInstance = new HttpTaskExecutor();
		return mInstance;
	}

	public void clearInstance() {
		if (mExecThreadTool != null) {
			mExecThreadTool.shutdownNow();
		}
		mExecThreadTool = null;
		mInstance = null;
	}

	
	public void execute(java.lang.Runnable command) {
        if (null == command)
            throw new NullPointerException();
        if (null == mExecThreadTool)
        	//mExecThreadTool = Executors.newSingleThreadExecutor();
        mExecThreadTool = Executors.newFixedThreadPool(FIX_THREAD_POOL_COUNT);
		try{
			mExecThreadTool.execute(command);
		} catch(RejectedExecutionException e){
			mExecThreadTool = null;
			//try again
			//mExecThreadTool = Executors.newSingleThreadExecutor();
			mExecThreadTool = Executors.newFixedThreadPool(FIX_THREAD_POOL_COUNT);
			try{
				mExecThreadTool.execute(command);
			} catch(RejectedExecutionException e1){
				//if still failed. force exit;
				 throw e1;
			}
		}        
	}
}
